﻿using System;
using System.Threading.Tasks;
using System.ComponentModel;
using System.Threading;

namespace HobSoft.SoccerBet2014.Server.SiteManagerSchedule
{
    using Domain.Common.Site;
    using Domain.Common.Site.Component;
    using Domain.Common.Schedule;
    using Domain.Schedule;
    using Domain.Models.Site;
    using Domain.Configuration;
    using Domain.DataService;

    public class SiteManagerView : INotifyPropertyChanged, INotifyPropertyChanging
    {
        private readonly byte _bmID;
        public byte BmID
        {
            get
            {
                return _bmID;
            }
        }

        private readonly string _account;
        public string Account
        {
            get
            {
                return _account;
            }
        }

        private readonly string _password;
        private readonly SessionManagerBase _manager;
        private Timer timer;
        private SiteManagerView()
        {

        }

        public SiteManagerView(byte bmId, string account, string password, SessionManagerBase manager)
        {
            _bmID = bmId;
            _account = account;
            _password = password;
            _manager = manager;
            DisplayState = "初始.";
            OnSignup = false;
            timer = new Timer(new TimerCallback(timer_Elapsed), null, 0, 1000);
        }

        private void timer_Elapsed(object sender)
        {
            if (LastLiveRequest.HasValue)
                LiveCountdown = (int)(DateTime.Now - LastLiveRequest.Value).TotalSeconds;

            if (LastTodayRequest.HasValue)
                TodayCountdown = (int)(DateTime.Now - LastTodayRequest.Value).TotalSeconds;

            if (LastEarlyRequest.HasValue)
                EarlyCountdown = (int)(DateTime.Now - LastEarlyRequest.Value).TotalSeconds;
        }

        public async Task<bool> Signup()
        {
            if (_manager == null) return false;
            if (_manager.ValidSessionOnline(DateTime.Now.AddMinutes(-3)))
            {
                _manager.RecoverContext();
                var ckTask = _manager.CheckSession();
                if (ckTask.Exception != null || ckTask.IsCanceled)
                    return false;
                await ckTask;
                if (ckTask.Result)
                {
                    DisplayState = "返回登陆成功。";
                    OnSignup = true;
                    await _manager.RequestMainPage();
                    return true;
                }
            }

            var startTask = _manager.Start();
            try
            {
                var onStart = await startTask;
                if (!onStart)
                {
                    DisplayState = "登陆页面错误。";
                    return false;
                }
            }
            catch
            {
                DisplayState = "登陆页面错误。";
                return false;
            }
            if(startTask.IsCanceled||startTask.Exception!=null)
            {
                DisplayState = "登陆页面错误。";
                return false;
            }

            var task = _manager.Signup(_password);
            var result = await task;
            if (task.IsCanceled || task.Exception != null) return false;
            if (_manager.LoginState == LoginState.Logined && result)
            {
                OnSignup = true;
                DisplayState = "登陆成功。";
                return true;
            }
            return false;
        }

        public void Start(ITimer timer,ScheduleConfiguration config)
        {
            _manager.SetSchedule(timer, config);
            if (OnSignup)
                _manager.StartSchedule();
        }

        public void Stop()
        {
            if (_manager.EnableTimerSchedule)
                _manager.StopSchedule();
        }

        protected virtual bool CheckLoginState()
        {
            if (_manager.LoginState != LoginState.Logined)
            {
                OnSignup = false;
                DisplayState = "登陆超时";
                return false;
            }
            return true;
        }

        protected DateTime? LastReadyRequest { get; set; }
        private int _liveCountdown;
        public int LiveCountdown
        {
            get
            {
                return _liveCountdown;
            }
            protected set
            {
                if (_liveCountdown == value) return;
                RaisePropertyChanging("LiveCountdown");
                _liveCountdown = value;
                RaisePropertyChanged("LiveCountdown");
            }
        }
        public DateTime? LastLiveRequest
        {
            get
            {
                return _manager.ScheduleRequestLog == null ? null : _manager.ScheduleRequestLog.LastLiveRequest;
            }
        }
        private int _todayCountdown;
        public int TodayCountdown
        {
            get
            {
                return _todayCountdown;
            }
            protected set
            {
                if (_todayCountdown == value) return;
                RaisePropertyChanging("TodayCountdown");
                _todayCountdown = value;
                RaisePropertyChanged("TodayCountdown");
            }
        }
        public DateTime? LastTodayRequest
        {
            get
            {
                return _manager.ScheduleRequestLog == null ? null : _manager.ScheduleRequestLog.LastTodayRequest;
            }
        }
        private int _earlyCountdown;
        public int EarlyCountdown
        {
            get
            {
                return _earlyCountdown;
            }
            protected set
            {
                if (_earlyCountdown == value) return;
                RaisePropertyChanging("EarlyCountdown");
                _earlyCountdown = value;
                RaisePropertyChanged("EarlyCountdown");
            }
        }
        public DateTime? LastEarlyRequest
        {
            get
            {
                return _manager.ScheduleRequestLog == null ? null : _manager.ScheduleRequestLog.LastEarlyRequest;
            }
        }

        private string displayState;
        public string DisplayState
        {
            get
            {
                return displayState;
            }
            set
            {
                if (displayState == value) return;
                RaisePropertyChanging("DisplayState");
                displayState = value;
                RaisePropertyChanged("DisplayState");
            }
        }

        private bool onSignup;
        public bool OnSignup
        {
            get
            {
                return onSignup;
            }
            protected set
            {
                if (onSignup == value) return;
                RaisePropertyChanging("OnSignup");
                onSignup = value;
                RaisePropertyChanged("OnSignup");
            }
        }


        protected virtual void RaisePropertyChanged(string propertyName)
        {
            if (PropertyChanged != null)
                PropertyChanged(this, new PropertyChangedEventArgs(propertyName));
        }

        protected virtual void RaisePropertyChanging(string propertyName)
        {
            if (PropertyChanging != null)
                PropertyChanging(this, new PropertyChangingEventArgs(propertyName));
        }

        public event PropertyChangedEventHandler PropertyChanged;

        public event PropertyChangingEventHandler PropertyChanging;
    }
}
